#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright @ 2014 OPS, Qunar Inc. (qunar.com)
#
# Author: tingfang.bao <tingfang.bao@qunar.com>
# DateTime: 15-3-6 下午6:44
"""
URL:METHOD:DESC
/users/     :   get     :get a list of all users
/users/     :   post    :create a new user
/users/<id> :   get     :show a user
/users/<id> :   put     :update a user
/users/<id> :   delete  : delete a user

"""
from flask import Flask
from flask.views import MethodView

app = Flask(__name__)


# noinspection PyMethodMayBeStatic
class UserAPI(MethodView):
    def get(self, user_id):
        if user_id is None:
            return str(['u1', 'u2'])
        else:
            return 'user id=%s' % user_id

    def post(self):
        # 创建参数通过request获取
        return 'create one user'

    def delete(self, user_id):
        print 'deleted %s' % user_id

    def put(self, user_id):
        print 'updated %s' % user_id


def register_api(view, endpoint, url, pk='id', pk_type='int'):
    view_func = view.as_view(endpoint)
    app.add_url_rule(url, defaults={pk: None}, view_func=view_func, methods=['GET'])
    app.add_url_rule(url, view_func=view_func, methods=['POST', ])
    app.add_url_rule('%s<%s:%s>' % (url, pk_type, pk), view_func=view_func, methods=['PUT', 'DELETE'])


# user_view = UserAPI.as_view('user_api')
# app.add_url_rule('/users/', defaults={'user_id': None}, view_func=user_view, methods=['GET'])
# app.add_url_rule('/users/', view_func=user_view, methods=['POST'])
# app.add_url_rule('/users/', defaults={'user_id': None}, view_func=user_view, methods=['GET', 'PUT', 'DELETE'])
register_api(UserAPI, 'user_api', '/users/', pk='user_id')

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=8080)